<template>
  <div>
    <img class="headerimg"
         src="https://xd-video-pc-img.oss-cn-beijing.aliyuncs.com/xdclass_pro/bannner/1901/learn.png"
         alt="">
    <cube-form :model="model"
               :schema="schema"
               @submit="submitHandler">
    </cube-form>
    <cube-button class="register"
                 @click="register">注册</cube-button>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  name: 'Login',
  data () {
    return {
      model: {
        username: '',
        password: ''
      },
      schema: {
        fields: [
          //用户名配置
          {
            type: 'input',
            modelKey: 'username',
            label: '用户名',
            props: {
              placeholder: '请输入用户名',
            },
            rules: {
              //校验规则
              required: true,
              type: 'string',
              min: 3,
              max: 15,
            },
            trigger: 'blur',
            messages: {
              required: '用户名不能为空',
              min: '用户名不能少于3个字符',
              max: '用户名不能大于15个字符'
            }
          },
          //密码配置
          {
            type: 'input',
            modelKey: 'password',
            label: '密码',
            props: {
              placeholder: '请输入密码',
              type: 'password',
              eye: {
                open: false,
              }
            },
            rules: {
              required: true,
            },
            trigger: 'blur',
          },
          {
            type: 'submit',
            label: '登录'
          }
        ]
      }
    }
  },
  methods: {
    async submitHandler (e) {
      e.preventDefault()
      try {
        const result = await axios.get('/api/login', { params: this.model })
        if (result.code == '0') {
          console.log('1')
          this.$store.commit('setToken', result.token)
          window.localStorage.setItem('token', result.token)
          //判断路由是否带参，带参就去指定路由
          if (this.$route.query.redirect) {
            console.log(this.$route.query.redirect)
            this.$router.replace({ path: this.$route.query.redirect })
          } else {
            this.$router.replace({ path: '/botnav/index' })
          }
        } else {
          alert(result.message)
        }
      } catch (err) {
        console.log(err)
      }
    },
    register () {
      this.$router.push({ path: '/register' })
    }
  }
}
</script>

<style lang="stylus" scoped>
.headerimg
  height: 150px
  width: 100%
.register
  width: 93%
  margin: 0 auto
</style>


